package agency.web.app.service.impl;


import java.util.ArrayList;
import java.util.List;

import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import agency.web.app.domain.User;
import agency.web.app.repository.UserDao;
import agency.web.app.service.UserService;

@Service
@Transactional
public class UserServiceImpl implements UserService {
	
	@Autowired
	private UserDao userRepository;

	public boolean isAgent(User u){
		return u.getUserType().contains("Agent");
	}
	public boolean isClient(User u){
		return u.getUserType().contains("Client");
	}
	public void addUser(User u) {
		userRepository.add(u);
		
	}
	public void modifyUser(User u) {
		userRepository.modify(u);
		
	}
	public User findUserById(int id) {
		return userRepository.findById(id);
	}
	public List<User> findUserByName(String name) {
		Criterion criterion = Restrictions.eq("name",name );
		List<User> users = userRepository.findByCriteria(criterion);
		return  users;
	}

	public void deleteUserById(int id) {
		userRepository.delete(id);
		
	}
	public void deleteUser(User c) {
		userRepository.delete(c);
		
	}
	public User userRegistration(String login, String password) {
		return userRepository.userRegistration(login, password);
	}
	public void logoutUser(int userId) {
		// TODO Auto-generated method stub
		
	}
	public List<User> findAllAgents() {
		List<User> users = userRepository.findAll();
		List<User> list = new ArrayList<User>();
		for (User u:users){
			if (isAgent(u))
				list.add( u);
		}
		return list;
	}
	public List<User> findAgentByClient(User client) {
		Criterion criterion = Restrictions.eq("userId",client.getUserId() );
		List<User> users = userRepository.findByCriteria(criterion);
		List<User> list = new ArrayList<User>();	
		for (User u:users){
			if (isAgent(u))
				list.add(u);
		}
		return  list;
	}
	public List<User> findAllClients() {
		List<User> users = userRepository.findAll();
		List<User> list = new ArrayList<User>();
		for (User u : users) {
			if (isClient(u))
				list.add(u);
		}
		return list;
	}
	public List<User> findClientsByAgent(User agent) {
		
		List<User> users = userRepository.findAll();
		List<User> list = new ArrayList<User>();	
		for (User u:users){
			if (isClient(u)&& ((u.getAgent().getUserId()) == agent.getUserId()))
				list.add(u);
		}
		return  list;
	}
	

}
